package pl.shenlon.poker.gui.testhands;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Scanner;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.DefaultTableModel;

import net.miginfocom.swing.MigLayout;
import pl.shenlon.assets.Assets;
import pl.shenlon.poker.game.TestHand;

public class TestHandsManagerDialog extends JDialog {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4344881061576821457L;

	private TestHandsCreationDialog creationDialog;

	private JButton deleteButton, insertButton, loadButton, saveButton,
			cancelButton, submitButton;

	private JFileChooser fileChooser;

	private final FileFilter testHandFileFilter;

	private JTable testHandsTable;

	private DefaultTableModel testHandsTableModel;

	private JScrollPane testHandsTableScrollPane;

	public TestHandsManagerDialog() {
		super();
		initComponent();
		pack();
		setModal(true);
		setTitle("Zarządzanie rękami testowymi");
		testHandFileFilter = new TestHandFileFilter();
		setLocationRelativeTo(null);
		setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
		setResizable(false);
	}

	private void addRow() {
		if (creationDialog == null) {
			creationDialog = new TestHandsCreationDialog();
		}
		creationDialog.setVisible(true);
		TestHand createdHand = creationDialog.getCreatedHand();
		if (createdHand == null) {
			return;
		}
		Object[] rowData = {
				createdHand.getPlayerACards(),
				createdHand.getPlayerBCards(),
				createdHand.getTableCards(),};
		testHandsTableModel.addRow(rowData);
	}

	private void initComponent() {
		Container contentPane = getContentPane();
		contentPane.setLayout(new MigLayout("filly"));

		loadButton = new JButton((ImageIcon) Assets.get("@icons/load"));
		loadButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent event) {
				loadFromFile();
			}
		});

		saveButton = new JButton((ImageIcon) Assets.get("@icons/save"));
		saveButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent event) {
				saveToFile();
			}
		});

		insertButton = new JButton((ImageIcon) Assets.get("@icons/add"));
		insertButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent event) {
				addRow();
			}
		});

		deleteButton = new JButton((ImageIcon) Assets.get("@icons/delete"));
		deleteButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				removeRows(testHandsTable.getSelectedRows());

			}
		});

		contentPane.add(loadButton, "split 4");
		contentPane.add(saveButton);
		contentPane.add(insertButton);
		contentPane.add(deleteButton, "wrap");

		Object[] columnIdentifiers = new Object[]{
				"Ręka pierwszego gracza",
				"Ręka drugiego gracza",
				"Karty na stole",};

		testHandsTableModel = new DefaultTableModel(0, 3) {
			/**
			 * 
			 */
			private static final long serialVersionUID = -2034944787789823069L;

			@Override
			public boolean isCellEditable(int row, int col) {
				return false;
			}
		};
		testHandsTableModel.setColumnIdentifiers(columnIdentifiers);
		testHandsTable = new JTable(testHandsTableModel);
		testHandsTable.setFillsViewportHeight(true);
		testHandsTableScrollPane = new JScrollPane(testHandsTable);

		contentPane.add(testHandsTableScrollPane, "grow, push, wrap");

		cancelButton = new JButton("Anuluj");
		cancelButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent event) {
				setVisible(false);
			}
		});

		submitButton = new JButton("Zatwierdź zmiany");
		submitButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent event) {
				setVisible(false);

			}
		});

		contentPane.add(submitButton, "split 2, w 50%, span");
		contentPane.add(cancelButton, "w 50%, wrap");
		getRootPane().setDefaultButton(cancelButton);
	}

	private void loadFromFile() {
		if (fileChooser == null) {
			fileChooser = new JFileChooser();
			fileChooser.setAcceptAllFileFilterUsed(false);
			fileChooser.setFileFilter(testHandFileFilter);
			fileChooser.setCurrentDirectory(new File("./data/testhands"));
		}

		int option = fileChooser.showOpenDialog(this);
		if (option == JFileChooser.APPROVE_OPTION) {
			File file = fileChooser.getSelectedFile();
			testHandsTableModel.setRowCount(0);
			Scanner in = null;
			try {
				in = new Scanner(file, "UTF-8");
				while (in.hasNextLine()) {
					String line = in.nextLine();
					TestHand testHand = new TestHand(line);
					testHandsTableModel.addRow(new Object[]{
							testHand.getPlayerACards(),
							testHand.getPlayerBCards(),
							testHand.getTableCards(),});
				}
			} catch (IOException ex) {
				JOptionPane
						.showMessageDialog(
								this,
								"Wystąpił błąd w trakcie wczytywania pliku, spróbuj ponownie później.",
								"Błąd", JOptionPane.ERROR_MESSAGE);
			} catch (IllegalArgumentException ex) {
				JOptionPane
						.showMessageDialog(
								this,
								"Plik zawiera niepoprawne dane. Nie nastąpi jego wczytanie",
								"Błąd", JOptionPane.ERROR_MESSAGE);
			} finally {
				in.close();
			}
		}
	}

	private void removeRows(int[] rows) {
		int choice = JOptionPane.showConfirmDialog(this,
				"Czy na pewno chcesz usunąć wybrane ręce testowe?",
				"Potwierdzenie", JOptionPane.OK_CANCEL_OPTION);
		if (choice == JOptionPane.CANCEL_OPTION) {
			return;
		}
		for (int i = rows.length - 1; i >= 0; i--) {
			testHandsTableModel.removeRow(rows[i]);
		}
	}

	private void saveToFile() {
		if (fileChooser == null) {
			fileChooser = new JFileChooser();
			fileChooser.setAcceptAllFileFilterUsed(false);
			fileChooser.setFileFilter(testHandFileFilter);
			fileChooser.setCurrentDirectory(new File("./data/testhands"));
		}
		int option = fileChooser.showSaveDialog(this);
		if (option == JFileChooser.APPROVE_OPTION) {
			File file = fileChooser.getSelectedFile();
			if (!file.getName().endsWith(
					TestHandFileFilter.TEST_HAND_FILE_EXTENSION)) {
				file = new File(file.getPath() + "."
						+ TestHandFileFilter.TEST_HAND_FILE_EXTENSION);
			}
			BufferedWriter out = null;
			try {
				out = new BufferedWriter(new OutputStreamWriter(
						new FileOutputStream(file), "UTF-8"));
				for (int i = 0; i < testHandsTableModel.getRowCount(); i++) {
					String line = testHandsTableModel.getValueAt(i, 0) + " "
							+ testHandsTableModel.getValueAt(i, 1) + " "
							+ testHandsTableModel.getValueAt(i, 2);
					out.write(line);
					out.newLine();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			} finally {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}